import {
  getUserDrugInfo,
  setDrugInfo
} from '../../../../api/medicine/medicine.js'
import Toast from '@vant/weapp/lib/toast/toast';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    windowHeight: undefined, //屏幕高度
    windowWidth: undefined, //屏幕宽度
    margintop: "",
    funcrowheight: "",
    tabbarHeight: undefined, //tabbar高度
    safeBottomHeight: undefined, //苹果底部横条高度
    topHeight: undefined,
    showCalendar: false,
    calendarText: '',
    minDate: new Date(2010, 0, 1).getTime(),
    maxDate: new Date(2010, 0, 31).getTime(),
    drugName: '', //药物名称
    drugDosage: '',//药物用量
    drugUnit: '',//药物单位
    cyChecked: false,
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    // 获取当前日期
    let currentDate = new Date();
    let currentYear = currentDate.getFullYear(); // 获取当前年份
    let currentMonth = currentDate.getMonth(); // 获取当前月份（注意：月份从 0 开始，所以需要加 1）
    let currentDay = currentDate.getDate(); // 获取当前日期
    // 获取当前月份的天数
    let daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    // 使用当前日期来替换示例中的固定日期，并计算最大日期
    let minDate = new Date(currentYear, currentMonth, currentDay).getTime();
    let maxDate = new Date(currentYear, currentMonth, currentDay + daysInMonth - currentDay).getTime();

    const {
      height,
      top
    } = wx.getMenuButtonBoundingClientRect();
    this.setData({
      windowHeight: app.globalData.windowHeight,
      windowWidth: app.globalData.windowWidth,
      tabbarHeight: app.globalData.tabbarHeight,
      safeBottomHeight: app.globalData.safeBottomHeight,
      topHeight: app.globalData.topHeight,
      margintop: top,
      funcrowheight: height,
      minDate: minDate,
      maxDate: maxDate,
      userInfo: wx.getStorageSync('userInfo')
    })

    getUserDrugInfo(this.data.userInfo.token).then((res)=>{
      console.log(res)
      this.setData({
        calendarText: res.lastTimeDrug,
        defaultDate: Date.parse(res.lastTimeDrug),
        interval: res.interval,
        cyChecked: res.isOpen == 0?false:true,
        drugName: res.drugName,
        drugDosage: res.drugDosage,
        drugUnit: res.drugUnit
      }) 
    })

  },
  showCalendarFunc() {
    this.setData({
      showCalendar: true
    });
  },
  onClose() {
    this.setData({
      showCalendar: false
    });
  },
  onConfirm(event) {
    console.log(event)
    this.setData({
      showCalendar: false,
      calendarText: `选择了 ${event.detail.length} 个日期`,
    });
  },

  onChangeCy({detail}) {
    if (detail) {
      wx.showModal({
        title: '复查提醒',
        content: '是否开启微信提醒？',
        success: (res) => {
          if (res.confirm) {
            this.setData({
              cyChecked: detail
            });
          }
        },
      });
    } else {
      this.setData({
        cyChecked: false
      });
    }
  },
  onConfirm(event) {
    console.log(event)
    this.setData({
      showCalendar: false,
      calendarText: this.formatDate(event.detail)
    });
  },

  formatDate(date) {
    date = new Date(date);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },
  bindInput(e){
    this.setData({interval: e.detail.value})
  },

  bindDrugDosageInput(e){
    this.setData({drugDosage: e.detail.value})
  },
  bindDrugUnitInput(e){
    this.setData({drugUnit: e.detail.value})
  },
  bindDrugNameInput(e){
    this.setData({drugName: e.detail.value})
  },

  saveDrugInfo(){
    if (this.data.interval == '') {
      Toast.fail('请输入间隔');
      return
    }
    if (this.data.calendarText == '') {
      Toast.fail('请选择日期');
      return
    }
    if (this.data.drugName == '') {
      Toast.fail('请输入名称');
      return
    }
    if (this.data.drugDosage == '') {
      Toast.fail('请输入用量');
      return
    }
    if (this.data.drugUnit == '') {
      Toast.fail('请输入单位');
      return
    }
    let drugInfo = {
      token: this.data.userInfo.token,
      interval: this.data.interval,
      lastTimeDrug: this.data.calendarText,
      isOpen: this.data.cyChecked==false?0:1,
      drugName: this.data.drugName,
      drugDosage: this.data.drugDosage,
      drugUnit: this.data.drugUnit
    }
    setDrugInfo(drugInfo).then((res)=>{
      if(res){
        Toast.success('设置成功');
        setTimeout(()=>{
          wx.navigateBack()
        },2000)
      }else{
        Toast.fail('Error!');
      }
    })
  },
})